using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Modules.NBrightEspace.Components;
using DotNetNuke.Services.Exceptions;
using NBrightCore.common;
using NBrightCore.render;
using NBrightDNN;

namespace DotNetNuke.Modules.NBrightEspace
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditNBrightEspace class is used to manage content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class Dashboard : EspaceModuleBase
    {

        #region Event Handlers

        override protected void OnInit(EventArgs e)
        {
           
            base.OnInit(e);
           
            var strListHeader = TemplCtrl.GetTemplateData("dashESTIMATES_ListH.html", Utils.GetCurrentCulture());
            var strListBody = TemplCtrl.GetTemplateData("dashESTIMATES_List.html", Utils.GetCurrentCulture());
            var strListFooter = TemplCtrl.GetTemplateData("dashESTIMATES_ListF.html", Utils.GetCurrentCulture());

            rpEstimates.HeaderTemplate = new GenXmlTemplate(strListHeader);
            rpEstimates.ItemTemplate = new GenXmlTemplate(strListBody);
            rpEstimates.FooterTemplate = new GenXmlTemplate(strListFooter);

            strListHeader = TemplCtrl.GetTemplateData("dashPROJECT_ListH.html", Utils.GetCurrentCulture());
            strListBody = TemplCtrl.GetTemplateData("dashPROJECT_List.html", Utils.GetCurrentCulture());
            strListFooter = TemplCtrl.GetTemplateData("dashPROJECT_ListF.html", Utils.GetCurrentCulture());

            rpProjects.HeaderTemplate = new GenXmlTemplate(strListHeader);
            rpProjects.ItemTemplate = new GenXmlTemplate(strListBody);
            rpProjects.FooterTemplate = new GenXmlTemplate(strListFooter);

            strListHeader = TemplCtrl.GetTemplateData("dashTASKS_ListH.html", Utils.GetCurrentCulture());
            strListBody = TemplCtrl.GetTemplateData("dashTASKS_List.html", Utils.GetCurrentCulture());
            strListFooter = TemplCtrl.GetTemplateData("dashTASKS_ListF.html", Utils.GetCurrentCulture());

            rpTasks.HeaderTemplate = new GenXmlTemplate(strListHeader);
            rpTasks.ItemTemplate = new GenXmlTemplate(strListBody);
            rpTasks.FooterTemplate = new GenXmlTemplate(strListFooter);

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (Page.IsPostBack == false)
            {
                PageLoad();
            }
        }

        private void PageLoad()
        {
            try
            {
                // Do Estimate list
                var strFilter = " and [XMLData].value('(genxml/checkbox/chkaccepted)[1]','nvarchar(10)') = 'False' ";
                strFilter += " and [XMLData].value('(genxml/checkbox/chkarchived)[1]','nvarchar(10)') = 'False' ";
                var cutoffDate = String.Format("{0:u}",DateTime.Now.AddDays(-5));
                strFilter += " and ISDATE([XMLData].value('(genxml/textbox/datevalid)[1]','nvarchar(max)')) = 1 ";
                strFilter += " and ([XMLData].value('(genxml/textbox/datevalid)[1]','datetime') >= convert(datetime,'" + cutoffDate.Substring(0,10) + "') )";
                strFilter += "and [XMLData].value('(genxml/textbox/datevalid)[1]','nvarchar(max)') like '%-%'"; // we need this to dal with isdate returning true for false dates.

                var l = GetList(PortalId, ModuleId, "ESTIMATES", strFilter, " order by [XMLData].value('(genxml/textbox/dateestimate)[1]','nvarchar(max)') ");
                rpEstimates.Visible = true;
                rpEstimates.DataSource = l;
                rpEstimates.DataBind();

                // Do Projects List
                strFilter = " and [XMLData].value('(genxml/radiobuttonlist/rblstatus)[1]','nvarchar(10)') = '6' ";
                l = GetList(PortalId, ModuleId, "PROJECT", strFilter, " order by [XMLData].value('(genxml/textbox/txtestenddate)[1]','nvarchar(max)') ");
                rpProjects.Visible = true;
                rpProjects.DataSource = l;
                rpProjects.DataBind();

                // Do Task List
                strFilter = " and [XMLData].value('(genxml/radiobuttonlist/rblowner)[1]','nvarchar(50)') = '" + UserInfo.DisplayName + "' ";
                strFilter += " and [XMLData].value('(genxml/checkbox/chkcompleted)[1]','nvarchar(10)') = 'False' ";
                strFilter += " and [XMLData].value('(genxml/dropdownlist/ddlstatus)[1]','nvarchar(10)') <= '3' ";                
                l = GetList(PortalId, ModuleId, "TASKS", strFilter, " order by ModifiedDate DESC ");
                if (l.Count == 0)
                {
                    rpTasks.Visible = false;                    
                }
                else
                {
                    rpTasks.Visible = true;
                    rpTasks.DataSource = l;
                    rpTasks.DataBind();                    
                }


            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }



        #endregion

        #region  "Events "

        protected void CtrlItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var cArg = e.CommandArgument.ToString();

            switch (e.CommandName.ToLower())
            {
                case "editestimate":
                    Response.Redirect(EditUrl("itemid", cArg, "ESTIMATES"), true);
                    break;
                case "editproject":
                    Response.Redirect(EditUrl("itemid", cArg, "PROJECT"), true);
                    break;
                case "edittask":
                    Response.Redirect(EditUrl("itemid", cArg, "TASKS"), true);
                    break;
                case "markcompleted":
                    MarkCompleted(cArg, "True");
                    Response.Redirect(EditUrl("dashboard"));
                    break;
                case "marknotcompleted":
                    MarkCompleted(cArg, "False");
                    Response.Redirect(EditUrl("dashboard"));
                    break;
            }

        }

        private void MarkCompleted(string itemId, string value)
        {
            if (Utils.IsNumeric(itemId))
            {
                var objCtrl = new EspaceController();
                var oInfo = ObjCtrl.Get(Convert.ToInt32(itemId));
                if (oInfo != null)
                {
                    oInfo.XMLData = GenXmlFunctions.SetGenXmlValue(oInfo.XMLData, "genxml/checkbox/chkcompleted", value, false);
                    oInfo.XMLData = GenXmlFunctions.SetGenXmlValue(oInfo.XMLData, "genxml/hidden/completeddate", DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture), false);
                    objCtrl.Update(oInfo);
                }
            }
        }

        #endregion


    }

}